<template>
  <div class="resources-container">
    <div class="search-bar">
      <div class="search-bar-header">
        <el-button type="primary" @click="showPublishDialog">
          <el-icon><Plus /></el-icon>
          发布资源
        </el-button>
      </div>
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="资源名称" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.username" placeholder="发布者" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="借用状态">
            <el-option label="全部状态" value="" />
            <el-option label="可借用" :value="1" />
            <el-option label="已借出" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row :gutter="20" class="resource-list">
      <el-col :span="6" v-for="resource in resourceStore.resources" :key="resource.id">
        <el-card :body-style="{ padding: '0px' }" class="resource-card">
          <el-carousel height="200px" v-if="resource.resourceImageInfo?.length">
            <el-carousel-item v-for="image in resource.resourceImageInfo" :key="image.id">
              <img :src="image.imageUrl" class="resource-image">
            </el-carousel-item>
          </el-carousel>
          <div class="resource-info">
            <h3>{{ resource.name }}</h3>
            <p class="description">{{ resource.description }}</p>
            <div class="meta">
              <span>发布者: {{ resource.userInfo.username }}</span>
              <el-tag :type="resource.status === 1 ? 'success' : 'info'">
                {{ resource.status === 1 ? '可借用' : '已借出' }}
              </el-tag>
            </div>
            <div class="actions">
              <el-button type="primary" @click="viewDetail(resource.id)">查看详情</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 发布资源对话框 -->
    <el-dialog v-model="publishDialogVisible" title="发布资源" width="600px">
      <el-form :model="publishForm" :rules="publishRules" ref="publishFormRef" label-width="100px">
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="publishForm.name" placeholder="请输入资源名称" />
        </el-form-item>
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="publishForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="publishForm.location" placeholder="请输入资源位置" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="publishForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资源图片" prop="files">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="publishDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePublish" :loading="publishing">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useResourceStore } from '../stores/resource'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, UploadFile } from 'element-plus'

interface SearchParams {
  name: string
  username: string
  status: string | number
  page: number
  pageSize: number
  beginTime?: string
  endTime?: string
}

interface ResourceImage {
  id: number
  imageUrl: string
}

interface UserInfo {
  id: number
  username: string
}

interface Resource {
  id: number
  name: string
  description: string
  location: string
  status: number
  viewCount: number
  borrowCount: number
  userInfo: UserInfo
  resourceImageInfo?: ResourceImage[]
}

interface Category {
  id: number
  name: string
}

interface PublishForm {
  name: string
  description: string
  location: string
  categoryId: number | undefined
  files: File[]
}

const resourceStore = useResourceStore()
const router = useRouter()

const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const searchForm = ref({
  name: '',
  username: '',
  status: '',
  dateRange: [],
  page: 1,
  pageSize: 12
})

const publishDialogVisible = ref(false)
const publishing = ref(false)
const publishFormRef = ref<FormInstance>()
const fileList = ref<UploadFile[]>([])
const categories = ref<Category[]>([
  { id: 1, name: '图书' },
  { id: 2, name: '电子设备' },
  { id: 3, name: '体育用品' },
  { id: 4, name: '其他' }
])

const publishForm = ref<PublishForm>({
  name: '',
  description: '',
  location: '',
  categoryId: undefined,
  files: []
})

const publishRules = {
  name: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
    { max: 50, message: '名称最长为50个字', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入资源描述', trigger: 'blur' },
    { max: 100, message: '描述不能多于100字', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入资源位置', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

const loadResources = async () => {
  const params: SearchParams = {
    name: searchForm.value.name,
    username: searchForm.value.username,
    status: searchForm.value.status,
    page: currentPage.value,
    pageSize: pageSize.value
  }
  
  // 如果选择了日期范围，添加开始和结束日期参数
  if (searchForm.value.dateRange?.length === 2) {
    params.beginTime = searchForm.value.dateRange[0] + ' 00:00:00'
    params.endTime = searchForm.value.dateRange[1] + ' 23:59:59'
  }
  
  console.log('请求参数:', params)
  
  const result = await resourceStore.getResources(params)
  if (result) {
    total.value = result.total
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadResources()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    username: '',
    status: '',
    dateRange: [],
    page: 1,
    pageSize: 12
  }
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadResources()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadResources()
}

const viewDetail = (id: number) => {
  router.push(`/home/resource/${id}`)
}

const showPublishDialog = () => {
  publishDialogVisible.value = true
  publishForm.value = {
    name: '',
    description: '',
    location: '',
    categoryId: undefined,
    files: []
  }
  fileList.value = []
}

const handleFileChange = (uploadFile: UploadFile) => {
  if (uploadFile.raw) {
    publishForm.value.files.push(uploadFile.raw)
  }
}

const handlePublish = async () => {
  if (!publishFormRef.value) return
  
  await publishFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!publishForm.value.categoryId) {
        ElMessage.error('请选择分类')
        return
      }

      publishing.value = true
      try {
        const publishData = {
          name: publishForm.value.name,
          description: publishForm.value.description,
          location: publishForm.value.location,
          categoryId: publishForm.value.categoryId
        }
        const success = await resourceStore.publishResource(publishData, publishForm.value.files)
        if (success) {
          ElMessage.success('资源发布成功')
          publishDialogVisible.value = false
          loadResources()
        }
      } finally {
        publishing.value = false
      }
    }
  })
}

onMounted(() => {
  loadResources()
})
</script>

<style scoped>
.resources-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

.search-bar-header {
  margin-bottom: 16px;
}

.resource-list {
  margin-bottom: 20px;
}

.resource-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.resource-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.resource-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.resource-info {
  padding: 15px;
}

.resource-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.description {
  margin: 10px 0;
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
  font-size: 14px;
  color: #909399;
}

.actions {
  text-align: right;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 